package com.openharmony.filepicker.engine;

import com.openharmony.filepicker.ResourceTable;
import com.openharmony.filepicker.config.FilePickerManager;
import ohos.agp.components.Image;
import ohos.app.Context;

public class ImageLoadController {

    private static volatile ImageLoadController imageLoadController;

    private boolean enableGlide = false;
    private boolean enablePicasso = false;
    private ImageEngine engine = null;

    private ImageLoadController() {
        try {
            Class.forName("com.bumptech.glide.Glide");
            enableGlide = true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            enableGlide = false;
        }

        try {
            Class.forName("com.squareup.picasso.Picasso");
            enablePicasso = true;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            enablePicasso = false;
        }
    }

    public static ImageLoadController INSTANCE() {
        if (imageLoadController == null) {
            synchronized (ImageLoadController.class) {
                if (imageLoadController == null) {
                    imageLoadController = new ImageLoadController();
                }
            }
        }
        return imageLoadController;
    }

    public void load(Context context,
                     Image image,
                     String url,
                     int placeholder) {

        if (engine == null && !initEngine()) {
            if (placeholder <= 0) {
                image.setPixelMap(ResourceTable.Graphic_ic_unknown_file_picker);
            } else {
                image.setPixelMap(placeholder);
            }
            return;
        }

        if (engine != null) {
            engine.loadImage(context, image, url, placeholder);
        }
    }

    private boolean initEngine() {
        if (FilePickerManager.INSTANCE().getConfig().getCustomImageEngine() != null) {
            engine = FilePickerManager.INSTANCE().getConfig().getCustomImageEngine();
        }else if (enableGlide) {
            engine = new GlideEngine();
        } else if (enablePicasso) {
            engine = new PicassoEngine();
        } else {
            engine = null;
        }

        return engine != null;
    }

    public void reset() {
        engine = null;
    }
}
